<template>
	<!-- 多张图片上传 -->
	<div class="component-upload-image" :style="widthAndHeight">
		<el-upload class="imageList" action="" multiple :limit="limit" list-type="picture-card" :file-list="fileList"
			:auto-upload="false" :on-error="handleUploadError" :on-change="handleChange" :disabled="disabled" :class="{
				hide:
					this.fileList.length >= this.limit ||
					(disabled && this.fileList.length),
			}" v-loading="loading" :element-loading-text="isZip ? '正在进行图片压缩' : '上传中'">
			<span class="text-danger text-16px" v-if="disabled">(无)</span>
			<i class="el-icon-plus" v-else></i>
			<template v-slot:file="{ file }">
				<img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
				<span class="el-upload-list__item-actions" @click="handlePreview(file)">
					<span class="el-upload-list__item-preview">
						<i class="el-icon-zoom-in"></i>
					</span>
					<span v-if="!disabled" class="el-upload-list__item-delete" @click.stop="handleDelete(file)">
						<i class="el-icon-delete"></i>
					</span>
				</span>
			</template>

		</el-upload>
		<!-- 上传提示 -->
		<div class="el-upload__tip" style="margin-top: 0" v-if="showTip">
			<template v-if="showMaxNum">
				最多可上传 <b style="color: #f56c6c">{{ limit }}</b> 张
			</template>
			<template v-if="widthPx && heightPx && ratio">
				，宽
				<b style="color: #f56c6c">{{ widthPx }}</b> 像素，高
				<b style="color: #f56c6c">{{ heightPx }}</b> 像素，建议宽高比为
				<b style="color: #f56c6c">{{ ratio }}</b>
			</template>
		</div>
		<!-- 图片描述 -->
		<div class="el-upload__tip" style="width: 100px; display: flex; justify-content: center" v-if="Description">
			<template>
				<b style="text-align: center">{{ Description }}</b>
			</template>
		</div>
		<el-dialog :visible.sync="priviewVisible" class="dialog" title="预览" append-to-body :lock-scroll="false" :close-on-click-modal="false"
			:close-on-press-escape="false" :modal="false" :width="dialogWidth" custom-class="preview-dialog" v-dialog-drag>
			<div v-if="priviewVisible">
				<viewer v-if="preview" :images="viewers" ref="viewer" class="w-700px h-640px">
					<img class="w-640px h-640px hidden" v-for="src in viewers" :key="src" :src="src" alt="image" />
				</viewer>
				<img v-else style="width: 100%; height: 100%" :src="priviewUrl" />
			</div>
			<!-- <img style="width: 100%; height: auto" :src="priviewUrl" alt="" /> -->
		</el-dialog>
	</div>
</template>

<script>
import * as imageConversion from "image-conversion";
import uploadFile from "@/utils/upload"; //上传

export default {
	model: {
		prop: "modelValue",
		event: "update:modelValue",
	},
	props: {
		modelValue: { type: String, default: "" },
		limit: { type: Number, default: 6 }, // 图片数量限制
		isShowTip: { type: Boolean, default: true }, // 是否显示提示
		showMaxNum: { type: Boolean, default: true }, // 是否显示最大张数提示
		disabled: { type: Boolean, default: false }, // 是否禁用
		width: { type: [Number, String], default: 100 }, // 上传框的宽
		height: { type: [Number, String], default: 100 }, // 上传框的高
		widthPx: { type: Number, default: 0 }, // 建议图片宽像素值
		heightPx: { type: Number, default: 0 }, // 建议图片高像素值
		ratio: { type: String, default: "" }, // 建议图片宽高比
		fileType: {
			type: Array,
			default: () => ["png", "jpg", "jpeg"],
		}, // 文件类型, 例如['png', 'jpg', 'jpeg']
		Description: {
			type: String,
			default: null,
		},
		preview: {
			type: Boolean,
			default: false,
		},
		viewers: {
			type: Array,
			default: () => [],
		},
		dialogWidth: {
			type: String,
			default: null,
		},
	},
	computed: {
		showTip() {
			return (
				!this.disabled &&
				this.isShowTip &&
				(this.showMaxNum || (this.heightPx && this.widthPx && this.ratio))
			);
		},
		// 动态渲染上传框的宽和高
		widthAndHeight() {
			return {
				"--height": this.height + "px",
				"--width": this.width + "px",
			};
		},
	},
	data() {
		return {
			firstTime: true,
			loading: false,
			isZip: false, //是否压缩
			dialogVisible: false,
			fileList: [],
			uploadList: [],
			priviewUrl: "",
			priviewVisible: false,
		};
	},
	// 首先将值转为数组
	watch: {
		modelValue: {
			handler(newValue) {
				this.fileList = [];
				if (newValue) {
					this.fileList = this.uploadList = Array.isArray(newValue)
						? newValue
						: this.modelValue.split(",").map((item) => ({ url: item }));
				} else {
					this.fileList = [];
				}
				this.firstTime = false;
			},
			immediate: true,
		},
	},
	methods: {
		upload(data) {
			let that = this;
			console.log("data", data);
			this.loading = true;
			uploadFile(data, data.name)
				.then((res) => {
					console.log("res666", res);
					that.uploadList.push({
						name: res.fileName,
						url: res.url,
						uid: data.uid,
					});
					console.log("uploadList", that.uploadList);
					that.$emit("update:modelValue", that.listToString());
					that.loading = false;
					that.uploadList = [];
				})
				.catch((err) => {
					that.loading = false;
				});
		},
		// 预览图片
		handlePreview(file) {
			console.log(file);
			if (!this.preview) {
				this.priviewUrl = file.response ? file.response.data.url : file.url;
				this.priviewVisible = true;
			} else {
				this.priviewVisible = true;
				if (this.preview) {
					let arr = JSON.parse(JSON.stringify(this.viewers));
					let afterArr = arr.filter((item) => item !== "");
					// let modelValueArr = this
					let index = afterArr.findIndex((item) => item === file.url);
					if (index > -1) {
						this.$nextTick(() => {
							console.log(this.$refs.viewer);
							this.$refs.viewer.$viewer.view(index);
						});
					}
				}
			}

		},
		// 上传成功
		handleUploadSuccess(res, file, fileList) {
			this.uploadList.push({
				name: res.data.name,
				url: res.data.url,
				uid: file.uid,
			});
			this.$emit("update:modelValue", this.listToString());
			this.loading = false;
		},
		// 删除图片
		handleDelete(file) {
			this.uploadList = this.uploadList.filter((item) => item.uid !== file.uid);
			console.log(this.uploadList);
			this.$emit("update:modelValue", this.listToString());
		},
		// 对象转成指定字符串分隔
		listToString() {
			return this.uploadList.map((item) => item.url || "").join(",");
		},
		handleChange(file) {
			console.log("file", file);
			let filetemp = file.raw;
			if (filetemp) {
				// 校检文件类型
				if (this.fileType.length) {
					let fileExtension = "";
					if (filetemp.name.lastIndexOf(".") > -1) {
						fileExtension = filetemp.name.slice(
							filetemp.name.lastIndexOf(".") + 1,
						);
					}
					const isTypeOk = this.fileType.some((type) => {
						if (filetemp.type.indexOf(type) > -1) return true;
						if (fileExtension && fileExtension.indexOf(type) > -1) return true;
						return false;
					});
					if (!isTypeOk) {
						this.$message.error(
							`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`,
						);
						return false;
					}
				}
			}
			this.loading = true;
			return new Promise((resolve, reject) => {
				console.log("压缩前", filetemp.size / 1024 / 1024);
				// 如果图片超过1.5m就压缩
				if (filetemp.size / 1024 / 1024 > 1.5) {
					this.isZip = true;
					imageConversion
						.compressAccurately(filetemp, {
							size: 750,
							scale: 0.5,
						})
						.then((res) => {
							let result = new File([res], filetemp.name, {
								type: res.type,
								lastModified: Date.now(),
							});
							console.log("压缩", res.size / 1024 / 1024);
							this.isZip = false;
							this.upload(result);
						});
				} else {
					console.log("没压缩", filetemp.size / 1024 / 1024);
					this.isZip = false;
					this.upload(filetemp);
				}
			});
		},
		handleUploadError() {
			this.loading = false;
			this.$message({
				type: "error",
				message: "上传失败",
			});
		},
	},
};
</script>

<style scoped lang="scss">
// .image {
// 	position: relative;

// 	.mask {
// 		opacity: 0;
// 		position: absolute;
// 		top: 0;
// 		width: 100%;
// 		transition: all 0.3s;
// 	}

// 	&:hover .mask {
// 		background-color: #000;
// 		opacity: 0.5;
// 	}
// }

// .el-upload__tip {
//     // margin-top: -10px !important;
// }
.hide ::v-deep .el-upload--picture-card {
	display: none !important;
}

::v-deep .el-upload-list__item {
	transition: none !important;
}

::v-deep .el-upload-list__item-actions {
	width: var(--width) !important;
	height: var(--height) !important;
}

::v-deep .el-upload-list__item {
	width: var(--width) !important;
	height: var(--height) !important;
	margin: 8px 8px 0 0;
}

::v-deep .el-upload-list__item-thumbnail {
	width: var(--width) !important;
	height: var(--height) !important;
	object-fit: cover;
}

::v-deep .el-upload--picture-card {
	width: var(--width) !important;
	height: var(--height) !important;
	line-height: var(--height) !important;
	margin-top: 8px;
	display: inline-block;
}

.image-slot {
	width: var(--width) !important;
	height: var(--height) !important;
	line-height: var(--height) !important;
}

::v-deep .el-upload {
	width: var(--width) !important;
	height: var(--height) !important;
}
.dialog ::v-deep .el-dialog__body {
  padding: 0 !important;	
}
</style>
